#include <errno.h>
#include <reent.h>
#include <sys/time.h>

#include "bflb_rtc.h"
#include "ls_rtc.h"


static struct bflb_device_s *rtc = NULL;

static uint32_t timestamp_base = 0;



/// @brief 
/// @param tp 
/// @return 
int ls_gettimeofday(struct timeval *tp)
{
    if (rtc == NULL) {
        rtc = bflb_device_get_by_name("rtc");
    }

    if (tp) {
        uint64_t ticks = bflb_rtc_get_time(rtc);
        tp->tv_sec = ticks / 32768 + timestamp_base;
        tp->tv_usec = (ticks & 0x7fff) * 31;
    }

 
    return 0;
}


/*****************************************************************************
* @brief        
* 
* @param[in]    reent       pointer to reentrant struct
* @param[in]    tp          pointer to timeval struct
* @param[in]    tzp         pointer to timezone struct
* 
* @retval int               
*****************************************************************************/
static int _ls_settimeofday_r(struct _reent *reent, const struct timeval *tp, const struct timezone *tzp)
{
    if (rtc == NULL) {
        rtc = bflb_device_get_by_name("rtc");
    }

    if (tp) {
        bflb_rtc_set_time(rtc, tp->tv_usec / 31);
        timestamp_base = tp->tv_sec;
    }

    return 0;
}



/// @brief 
/// @param tp 
/// @param tzp 
/// @return 
int ls_settimeofday(const struct timeval *tp)
{
    return _ls_settimeofday_r(_REENT, tp,NULL);
}
